/*
 * @Author: 袁十一
 * @Date: 2023-09-26 11:00:30
 * @LastEditTime: 2023-10-14 22:10:56
 * @LastEditors: Please set LastEditors
 * @Description:
 * @FilePath: \Vue3_admin_template\src\store\modules\user.ts
 * 初心不变，意志坚定
 */
import { defineStore } from 'pinia'
import { reqLogin, reqLogout, reqUserInfo } from '@/api/user'
import { UserState } from './types/type'
import {
  userInfoResponseData,
  loginFormData,
  loginResponseData,
} from '@/api/user/type'
import { GET_TOKEN, SET_TOKEN, REMOVE_TOKEN } from '@/util/token'
import { constantRoute } from '@/router/router'
const useUserStore = defineStore('user', {
  state: (): UserState => {
    return {
      token: GET_TOKEN(), //用户唯一标识
      menuRoutes: constantRoute, //仓库存储菜单需要的数组(路由)
      username: '',
      avatar: '',
    }
  },
  // 异步逻辑
  actions: {
    //用户登录的方法
    async userLogin(data: loginFormData) {
      const result: loginResponseData = await reqLogin(data)
      if (result.code == 200) {
        // console.log(result);
        this.token = result.data as string
        SET_TOKEN(result.data as string)
        return result.ok
      } else {
        return Promise.reject(new Error(result.data))
      }
    },
    //获取用户信息方法
    async userInfo() {
      const result: userInfoResponseData = await reqUserInfo()
      // console.log(result)
      if (result.code == 200) {
        this.username = result.data.name
        this.avatar = result.data.avatar
        return result.ok
      } else {
        return Promise.reject(result.message)
      }
    },
    async userLogout() {
      const result = await reqLogout()
      if (result.code == 200) {
        this.token = ''
        this.avatar = ''
        this.username = ''
        REMOVE_TOKEN()
        return 'ok'
      } else {
        return Promise.reject(new Error(result.message))
      }
    },
  },
  getters: {},
})
export default useUserStore
